<template>
  <div
    v-if="projectId"
    class="subscribe-block"
    :class="{ active: isSubscribed, hidden: !isHome }"
    @click.stop
  >
    <subscribe-mobile
      ref="sub"
      :projectId="projectId"
      :subText="subText"
      :unsubText="unsubText"
      @status-change="onStatusChange"
    ></subscribe-mobile>
  </div>
</template>

<script>
import tools from '@/lib/tools';
import { reqTrackPoolCustomStatus } from '@/apis/portfolio.api';
import { BASE_URL } from '@/config/pool';
import { Dialog } from '@atom/atom-ui';

export default {
  props: {
    // 是否需要校验跟踪池定制情况（股池需要，ETF不需要）
    checkTrackPool: {
      type: Boolean,
      default: false,
    },
    projectId: {
      type: Number,
      default: 0,
    },
    isHome: {
      type: Boolean,
      default: true,
    },
    refreshSub: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      isLock: false,
      isSubscribed: false,
    };
  },
  computed: {
    subText() {
      return this.isHome ? '已订阅' : '';
    },
    unsubText() {
      return this.isHome ? '+订阅' : '';
    },
  },
  watch: {
    refreshSub() {
      this.$refs.sub.updateSubText();
    },
  },
  methods: {
    openSub() {
      this.$refs.sub.getData();
    },
    onStatusChange(status) {
      this.isSubscribed = !status;
      if (this.isHome) {
        return;
      } else {
        const textContent = status ? '+订阅' : '已订阅';
        tools.setTitlebar(textContent, () => {
          this.onTitleBarClick();
        });
      }
    },

    // 点击顶部订阅栏
    onTitleBarClick() {
      if (this.checkTrackPool) {
        this.getTrackPoolStatus();
      } else {
        this.openSub();
      }
    },

    // 获取跟踪池定制状态
    async getTrackPoolStatus() {
      const portfolioId = window.getParam('portfolio_id');
      try {
        const res = await reqTrackPoolCustomStatus({ portfolio_id: portfolioId });
        if (res.status_code) {
          throw new Error(
            `servicePack/Subscribe.vue组件的getTrackPoolStatus的status_code错误，入参portfolio_id为${portfolioId}，响应为${JSON.stringify(
              res
            )}`
          );
        }
        // 检查是否已定制
        this.checkTrackPoolStatus(res.data);
      } catch (error) {
        tools.errorReport({
          name: `servicePack/Subscribe.vue组件的getTrackPoolStatus错误。${error.name}`,
          message: `portfolio_id为${portfolioId}。message：${error.message}`,
          stack: error.stack,
        });
      }
    },

    // 校验跟踪池定制状态
    checkTrackPoolStatus(data) {
      if (!data) {
        Dialog.confirm({
          title: '定制跟踪提醒',
          message: '您还未开启定制跟踪，定制策略之后可以选择订阅提醒方式，是否去定制？',
          confirmButtonText: '去定制',
        })
          .then(() => {
            this.isHome ? this.jumpTrackPool() : this.toggleTrackPool();
          })
          .catch(error => {
            tools.errorReport({
              name: `servicePack/Subscribe.vue组件的checkTrackPoolStatus错误。${error.name}`,
              message: error.message,
              stack: error.stack,
            });
          });
      } else {
        this.openSub();
      }
    },

    // 首页时，跳转详情页并打开定制弹窗
    jumpTrackPool() {
      location.href = `${BASE_URL}detailsServicePack?portfolio_id=${window.getParam(
        'portfolio_id'
      )}&activeTab=1`;
    },

    // 详情页时，打开定制弹窗
    toggleTrackPool() {
      const TRACK_POOL_TAB_INDEX = 1;
      this.$emit('setActiveTab', TRACK_POOL_TAB_INDEX);
    },
  },
};
</script>

<style lang="less" scoped>
.subscribe-block {
  width: 60px;
  height: 24px;
  border-radius: 2px;
  font-size: 14px;
  letter-spacing: 0;
  text-align: center;
  line-height: 24px;
  color: #ff2436;
  background: rgba(255, 36, 54, 0.1);
  &.active {
    color: var(--text-2);
    background: #f5f5f5;
  }
}
[theme-mode='black'] .subscribe-block.active {
  background: #292929;
}
.subscribe-block.hidden {
  background: transparent;
}
</style>
